#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File: main.py
# @Author: lotus163
# @Date: 2022/11/21
import uvicorn
from fastapi import FastAPI
from loguru import logger
from starlette.responses import FileResponse

from backend.config.setting import settings
from backend.register import logger_init, register_mount, register_exception, register_router, register_middleware, \
    register_cors, register_orm, register_redis, register_casbin

app = FastAPI(description=settings.DESCRIPTION, version=settings.VERSION, debug=settings.DEBUG,
              title=settings.TITLE, docs_url=settings.DOCS_URL, openapi_url=settings.OPENAPI_URL,
              redoc_url=settings.REDOC_URL)


async def create_app():
    """ 注册中心 """
    logger_init()  # 日志初始化

    register_mount(app)  # 挂载静态文件

    register_exception(app)  # 注册捕获全局异常

    register_router(app)  # 注册路由

    register_middleware(app)  # 注册请求响应拦截

    register_cors(app)  # 注册跨域请求

    await register_orm(app)  # 注册数据库

    await register_redis(app)  # 注册redis

    #register_casbin(app)  # 不使用casbin

    logger.info("startup over")  # 初始化日志


@app.on_event("startup")
async def startup():
    logger.info("startup")  # 初始化日志
    await create_app()  # 加载注册中心


@app.on_event("shutdown")
async def shutdown():
    pass


@app.get("/")
async def root():
    return "Welcome To RuoYi-FastAPI."


@app.get('/favicon.ico', include_in_schema=False)
def favicon():
    return FileResponse('favicon.ico')


if __name__ == '__main__':
    """
    app	运行的 py 文件:FastAPI 实例对象
    host	访问url，默认 127.0.0.1
    port	访问端口，默认 8080
    reload	热更新，有内容修改自动重启服务器
    debug	同 reload
    reload_dirs	设置需要 reload 的目录，List[str] 类型
    log_level	设置日志级别，默认 info
    """
    uvicorn.run(app='main:app', host=settings.UVICORN_HOST, port=settings.UVICORN_PORT, reload=settings.UVICORN_RELOAD)
